import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/face_model/certification_result_model.dart';
import 'package:yysk_app/pages/nft_pages/setting/face_recognition_webview_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'setting_real_name_auth_controller.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/net/http.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yysk_app/net/api/api_url.dart';

class SettingRealNameAuthPage extends GetView<SettingRealNameAuthController> {
  static const path = '/realNameAuth';

  SettingRealNameAuthPage({super.key});
  final GlobalController globalController = Get.find();

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    return PopScope(
      canPop: false,
      child: Scaffold(
        body: Stack(
          children: [
            SizedBox(
              width: context.width,
              child: ImageAssetWidget(
                width: 375.px,
                height: 812.px,
                imageUrl: 'static/images/bg.png',
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: 0.px, top: top, right: 0.px),
              child: Column(
                children: [
                  CustomAppBar2(
                    title: '实名认证',
                    context: context,
                    beforBack: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  Expanded(
                    child: ListView(
                      padding: EdgeInsets.fromLTRB(0.px, 0.px, 0.px, 0.px),
                      children: [
                        _info(context),
                        SizedBox(height: 12.px),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(height: 15),
                            Container(
                              padding: EdgeInsets.only(
                                left: 15,
                                top: 10,
                                bottom: 15,
                              ),
                              decoration: BoxDecoration(
                                gradient: LinearGradient(
                                  colors: [
                                    Color(0xFF1F2126),
                                    Color(0x001E2126),
                                  ], // 定义渐变颜色
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter,
                                ),
                                borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(12.px),
                                  topRight: Radius.circular(12.px),
                                ),
                              ),
                              child: _box(context),
                             
                            ),
                          ],
                        ),
                        SizedBox(height: 78.px),

                        Center(
                          child: ButtonWidget(
                            width: 322,
                            height: 54,
                            fontSize: 16.px,
                            fontColor: AppColors.backgroundColorBlack,
                            contentType: ContentType.text,
                            label: '立即认证',
                            onPressed: () {
                              _handleSubmit();
                            },
                          ),
                        ),
                         SizedBox(height: 12.px),
                         Center(
                          child: SizedBox(
                            width: 327.px,
                            child: Text('实名仅用于您是否为真人用户，平台不会将您的信息用于其他，请放心使用。',style: TextStyle(fontSize: 12.px,color: AppColors.backgroundColorGrey),),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _handleSubmit() {
    if (controller.infoDetail.value?.isPass == 2 ||
        controller.infoDetail.value?.isPass == 3) {
      http.netFetch<String>(
        ApiUrl.getFaceVerificationUrl,
        method: Method.post,
        success: (result) {
          if (result.data != null && result.data!.isNotEmpty) {
            Get.toNamed(
              '${FaceRecognitionWebviewPage.path}?url=${Uri.encodeComponent(result.data ?? '')}',
              arguments: {'url': Uri.encodeComponent(result.data ?? '')},
            );
          } else {
            showToast('人脸验证地址为空');
            return;
          }
        },
      );
    } else {
      if (controller.nameController.text.isEmpty) {
        showToast('请输入真实姓名');
        return;
      }
      if (isValidIDCard(controller.cardIdController.text) == false) {
        showToast('请输入正确的身份证号码');
        return;
      }
      http.netFetch<CertificationResultModel>(
        ApiUrl.putCertification,
        params: {
          'mobile': globalController.user.value?.userTel ?? '',
          'name': controller.nameController.text,
          'cardId': controller.cardIdController.text,
        },
        success: (result) {
          if (result.data?.flag == true) {
            if (result.data?.faceCheckUrl != null &&
                result.data!.faceCheckUrl!.isNotEmpty) {
              Get.toNamed(
                '${FaceRecognitionWebviewPage.path}?url=${Uri.encodeComponent(result.data?.faceCheckUrl ?? '')}',
                arguments: {
                  'url': Uri.encodeComponent(result.data?.faceCheckUrl ?? ''),
                },
              );
            } else {
              showToast('人脸验证地址为空');
              return;
            }
          } else {
            showToast('实名认证成功');
            globalController.getUserInfo(success: (p0) => {Get.back()});
          }
        },
      );
    }
  }

  bool isValidIDCard(String id) {
    // 15位身份证号码的正则表达式
    final RegExp id15Pattern = RegExp(r'^\d{15}$');
    // 18位身份证号码的正则表达式，最后一位可以是数字或X
    final RegExp id18Pattern = RegExp(
      r'^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\d{3}(\d|X)$',
    );

    // 判断是否为15位或18位数字
    if (id.length == 15 && id15Pattern.hasMatch(id)) {
      return true;
    } else if (id.length == 18 && id18Pattern.hasMatch(id)) {
      return true;
    } else {
      return false;
    }
  }

  _info(BuildContext context) {
    return Container(
      width: context.width,
      padding: EdgeInsets.fromLTRB(24.px, 0.px, 24.px, 0.px),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '即刻认证',
                style: TextStyle(color: AppColors.fontColor, fontSize: 20.px),
              ),
              SizedBox(height: 13.px),
              Text(
                '为您的合法权益保驾护航',
                style: TextStyle(
                  color: AppColors.backgroundColorGrey,
                  fontSize: 14.px,
                ),
              ),
            ],
          ),
          ImageAssetWidget(
            width: 127.px,
            height: 129.px,
            imageUrl: 'static/images/setting/complete_icon@2x.png',
          ),
        ],
      ),
    );
  }

  _box(BuildContext context) {
    return Container(
      width: context.width,
      padding: EdgeInsets.fromLTRB(24.px, 0.px, 24.px, 0.px),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(height: 14.px),
          Center(
            child: Text(
              '请您使用有效身份证信息认证',
              style: TextStyle(fontSize: 16.px, color: AppColors.fontColor),
            ),
          ),
          SizedBox(height: 34.px),
          _inputItem(context: context, txt: '手机号',enable:false,inputController: controller.phoneController,hintText: ''),
           _inputItem(context: context, txt: '姓名',inputController: controller.nameController,hintText: '请输入姓名'),
            _inputItem(context: context, txt: '身份证号',inputController: controller.cardIdController,hintText: '请输入身份证号'),
        ],
      ),
    );
  }

  _inputItem({required BuildContext context, String txt = '标题',bool enable =true ,required TextEditingController inputController ,String hintText='' }) {
    return Container(
      width: context.width,
      padding: EdgeInsets.fromLTRB(24.px, 0, 24.px, 0),
      margin: EdgeInsets.only(bottom: 12.px),
      decoration: BoxDecoration(
        color: Color.fromRGBO(31, 33, 38, 1),
        borderRadius: BorderRadius.circular(24.px),
      ),
      height: 45.px,

      child: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              width: 87.px,
              child: Text(
                txt,
                style: TextStyle(
                  color: AppColors.backgroundColorGrey,
                  fontSize: 14.px,
                ),
                textAlign: TextAlign.justify,
              ),
            ),
            Expanded(
              child: TextField(
                enabled: enable,
                controller: inputController,
                style: TextStyle(
                  fontSize: 14.px,
                  color: AppColors.fontColor,
                ),
                decoration: InputDecoration(
                  contentPadding: const EdgeInsets.symmetric(vertical: 14),
                  border: InputBorder.none,
                  hintText: hintText,
                  hintStyle: const TextStyle(color: AppColors.backgroundColorGrey),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
